package com.wq.jdk8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @Author: wangqiang20995
 * @Date:2019/9/2
 * @Description:
 * @Resource:
 */
public class SupplierDemo {

    private static class InnerSupplier {

        private String code;

        public InnerSupplier(String code) {
            this.code = code;
        }

        @Override
        public String toString() {
            return "InnerSupplier{" +
                    "code=" + code +
                    '}';
        }

        static {
            System.out.println("inner class do static init");
        }
        {
            System.out.println("inner class do constructor");
        }

        public void show() {
            System.out.println("I am InnerSupplier");
        }
    }

    public static void main(String[] args) {
//        callSupplier(() -> new InnerSupplier());
//        callInner(new InnerSupplier("1"));
        List<InnerSupplier> list = arrayToList(new String[]{"1","2","3","4","5"});
        System.out.println(list);
    }

    public static List<InnerSupplier> arrayToList(String[] nums){
        if (nums == null || nums.length > 1){
            return new ArrayList<>();
        }

        List<InnerSupplier> list = Arrays.stream(nums).map(num ->{
            InnerSupplier innerSupplier = new InnerSupplier(String.valueOf(num));
            return innerSupplier;
        }).collect(Collectors.toList());

        return list;
    }

    public static void callInner(InnerSupplier innerSupplier){
        innerSupplier.show();
    }

    public static void callSupplier(Supplier<InnerSupplier> supplier) {
        /**
         * 惰性初始化，语句输出的先后顺序如下
         * before call supplier...
         * inner class do static init
         * inner class do constructor
         * I am InnerSupplier
         * after call supplier...
         */
        try {
            System.out.println("before call supplier...");

            InnerSupplier inner = supplier.get();
            inner.show();
            System.out.println("after call supplier...");
        } catch (Throwable e) {
            System.out.println("throw error:" + e.getMessage());
        }
    }
}
